package org.ytor.core.sysapi.codegen.config;

import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码生成器的配置信息
 */
@Data
@Slf4j
@Component
public class CodeGeneratorConfig {

    /** 从 YAML 里加载的所有映射，结构为：
     * {
     *   "default": {...},
     *   "mysql":   { ... merged with default ... },
     *   "oracle":  { ... merged with default ... },
     *    ...
     * }
     */
    private Map<String, Map<String, String>> typeMappings = new HashMap<>();

    /**
     * 从Java到ts的映射
     */
    private Map<String, String> javaToTsMapper = new HashMap<>();

    @PostConstruct
    @SuppressWarnings("unchecked")
    public void init() {
        Yaml yaml = new Yaml();
        try (InputStream is = getClass()
                .getClassLoader()
                .getResourceAsStream("template/config.yml")) {

            Map<String, Object> root = yaml.load(is);
            Map<String, Map<String, String>> raw = (Map<String, Map<String, String>>) root.get("dbToJavaMapper");

            // 先把 default 原样放进来
            Map<String, String> defaultMap = raw.getOrDefault("default", Collections.emptyMap());
            typeMappings.put("default", new HashMap<>(defaultMap));

            // 再为每个数据库生成一份：default 覆盖 + 专属映射
            raw.forEach((db, specific) -> {
                if ("default".equalsIgnoreCase(db)) return;

                // 拷贝 default
                Map<String, String> merged = new HashMap<>(defaultMap);
                // 覆盖或添加专属
                merged.putAll(specific);
                typeMappings.put(db.toLowerCase(), merged);
            });

            log.info("dbToJavaMapper loaded mappings: {}", typeMappings.keySet());

            javaToTsMapper.putAll((Map<String, String>) root.get("javaToTsMapper"));
            log.info("javaToTsMapper loaded mappings: {}", javaToTsMapper.keySet());
        } catch (IOException e) {
            log.error("代码生成器初始化出错", e);
        }
    }

    /**
     * 根据数据库类型和列类型，查询对应的 Java 类型
     * @param dbType       比如 "mysql", "oracle"（不区分大小写）
     * @param columnType   直接用 database metadata 拿到的类型名称，如 "varchar", "tinyint(1)"，需要 trim()、toLowerCase()
     * @return Java 类型全名，比如 "java.lang.String"
     * @throws IllegalArgumentException 未找到映射时抛出
     */
    public String getJavaType(String dbType, String columnType) {
        String key = columnType.trim().toLowerCase();
        // 1. 先查指定 db
        Map<String, String> vendorMap = typeMappings.get(dbType.toLowerCase());
        if (vendorMap != null && vendorMap.containsKey(key)) {
            return vendorMap.get(key);
        }
        // 2. 再回退到 default
        Map<String, String> defaultMap = typeMappings.get("default");
        if (defaultMap != null && defaultMap.containsKey(key)) {
            return defaultMap.get(key);
        }
        return "Object";
    }

    public String getTsType(String javaType) {
        String key = javaType.trim().toLowerCase();
        return javaToTsMapper.getOrDefault(key, "any");
    }
}
